package io.libp2p.example.chat;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.widget.Toast;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class OpenUtils {

    public static void openBrowser(Context context, String url) {
        try {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setData(Uri.parse(url));

            context.startActivity(intent);
        } catch (Exception e) {
            Toast.makeText(context, "打开链接失败", Toast.LENGTH_SHORT).show();
        }
    }

    public static List<String> loadRecentMedia(Context context) {
        List<String> mediaPaths = new ArrayList<>();

        // 查询图片和视频（合并结果）
        Uri queryUri = MediaStore.Files.getContentUri("external");

        String[] projection = new String[]{
                MediaStore.Files.FileColumns.DATA,          // 文件路径（Android 10+ 可能为空）
                MediaStore.MediaColumns.DATE_ADDED,         // 添加时间
                MediaStore.Files.FileColumns.MEDIA_TYPE     // 媒体类型（图片/视频）
        };

        String selection = MediaStore.Files.FileColumns.MEDIA_TYPE + " IN (?, ?)";
        String[] selectionArgs = new String[]{
                String.valueOf(MediaStore.Files.FileColumns.MEDIA_TYPE_IMAGE),
                String.valueOf(MediaStore.Files.FileColumns.MEDIA_TYPE_VIDEO)
        };

        String sortOrder = MediaStore.MediaColumns.DATE_ADDED + " DESC";

        try (Cursor cursor = context.getContentResolver().query(
                queryUri,
                projection,
                selection,
                selectionArgs,
                sortOrder)) {

            if (cursor != null) {
                while (cursor.moveToNext()) {
                    // 处理路径兼容性（Android 10+ 需使用 RELATIVE_PATH + DISPLAY_NAME）
                    String path = cursor.getString(cursor.getColumnIndex(MediaStore.MediaColumns.DATA));

                    MyLog.D("loadRecentMedia path="+path);

                    File file = new File(path);

                    if(file.exists()) {
                        mediaPaths.add(path);
                    }

                    if(mediaPaths.size() >= 20) break;
                }
            }else{
                MyLog.W("loadRecentMedia cursor is NULL");
            }
        } catch (Exception e) {
            MyLog.W("loadRecentMedia Exception :"+e);
            e.printStackTrace();
        }

        return mediaPaths;
        // 使用 mediaPaths 处理结果（例如显示到 RecyclerView）
    }


}
